package com.huluobo.a2303mdmdemo.pages

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.google.gson.Gson
import com.huluobo.a2303mdmdemo.R
import com.huluobo.a2303mdmdemo.demo.RedPackRainView
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.hyphenate.EMCallBack
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMTextMessageBody
import com.hyphenate.util.DateUtils
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2025/9/4.
 */

data class ChatBean(val contact: String, val chatType: ChatType, val groupName: String = "")

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatPage(navHostController: NavHostController, json: String) {
    val chatBean = Gson().fromJson(json, ChatBean::class.java)

    //消息数据源
    val messageList = remember {
        SnapshotStateList<EMMessage>()
    }

    //发送的消息
    var messageString by remember {
        mutableStateOf("")
    }

    //发送消息进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //发送消息错误的图标
    var isShowError by remember {
        mutableStateOf(false)
    }

    //是否显示时间
    var isShowTime by remember {
        mutableStateOf(false)
    }

    //是否显示爱心雨
    var isShowLove by remember {
        mutableStateOf(false)
    }

    var isShowBottomDialog by remember {
        mutableStateOf(false)
    }

    //获取消息列表的状态
    val listState = rememberLazyListState()

    //控制滚动的协程作用域
    val coroutineScope = rememberCoroutineScope()

    //消息监听器
    val messageListener = EMMessageListener {
        messageList.addAll(it)
        //接收到新消息时,控制协程滚动到列表最下方
        coroutineScope.launch {
            listState.scrollToItem(messageList.size - 1)
        }
    }

    //通过联系人id拿到对应的会话列表
    val emConversation = EMClient.getInstance().chatManager().getConversation(chatBean.contact)
    //如果会话列表不为空,加载历史消息
    if (emConversation != null) {
        messageList.clear()
        messageList.addAll(emConversation.allMessages)
    }

    DisposableEffect(Unit) {
        //初始化时添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        onDispose {
            //页面销毁时,移除监听器
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    Scaffold(
        bottomBar = {
            OutlinedTextField(
                value = messageString,
                onValueChange = { messageString = it },
                Modifier.fillMaxWidth(),
                trailingIcon = {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(5.dp)
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.baseline_add_circle_outline_24),
                            contentDescription = "", modifier = Modifier.clickable {
                                isShowBottomDialog = true
                            }
                        )
                        Icon(imageVector = Icons.Default.Send, contentDescription = "", modifier = Modifier.clickable {
                            if (messageString.isNotEmpty()) {
                                isShowProgress = true
                                //构建一条文本消息
                                val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                                //设置消息类型,如果是群聊消息会自动切换
                                emMessage.chatType = chatBean.chatType
                                //发送消息不管成功失败都添加数据源
                                messageList.add(emMessage)
                                coroutineScope.launch {
                                    listState.scrollToItem(messageList.size - 1)
                                }
                                emMessage.setMessageStatusCallback(object : EMCallBack {
                                    override fun onSuccess() {
                                        //清空输入框
                                        messageString = ""
                                        isShowProgress = false
                                        isShowError = false
                                    }

                                    override fun onError(code: Int, error: String?) {
                                        Log.e("TagA", "发送消息失败:$code,$error")
                                        isShowProgress = false
                                        isShowError = true
                                    }
                                })
                                //向发送消息
                                EMClient.getInstance().chatManager().sendMessage(emMessage)
                            }
                        })
                    }
                })
        }
    ) {
        Column(
            modifier = Modifier
                .padding(it)
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            if (chatBean.chatType == ChatType.GroupChat) {
                BaseTitle(title = "与${chatBean.groupName}聊天", navHostController = navHostController)
            } else {
                BaseTitle(title = "与${chatBean.contact}聊天", navHostController = navHostController)
            }
            Spacer(modifier = Modifier.height(10.dp))
            LazyColumn(state = listState, content = {
//                items(messageList) { item ->
//                    ChatItem(message = item, isShowProgress)
//                }
                itemsIndexed(messageList) { index, item ->
                    if (index == 0) {
                        isShowTime = true
                    } else {
                        isShowTime =
                            !DateUtils.isCloseEnough(messageList[index].msgTime, messageList[index - 1].msgTime)
                    }
                    // index == messageList.lastIndex 当前index是否是数据源最后一个的下标
                    ChatItem(
                        message = item,
                        isShowProgress = isShowProgress,
                        isLast = index == messageList.lastIndex,
                        isShowError,
                        isShowTime
                    ) {
                        if (messageString.isNotEmpty()) {
                            isShowProgress = true
                            //构建一条文本消息
                            val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                            //设置消息类型,如果是群聊消息会自动切换
                            emMessage.chatType = chatBean.chatType
                            isShowError = false
                            messageList.removeAt(messageList.size - 1)
                            //发送消息不管成功失败都添加数据源
                            messageList.add(emMessage)
                            coroutineScope.launch {
                                listState.scrollToItem(messageList.size - 1)
                            }
                            emMessage.setMessageStatusCallback(object : EMCallBack {
                                override fun onSuccess() {
                                    //清空输入框
                                    messageString = ""
                                    isShowProgress = false
                                    isShowError = false
                                }

                                override fun onError(code: Int, error: String?) {
                                    Log.e("TagA", "发送消息失败:$code,$error")
                                    isShowProgress = false
                                    isShowError = true
                                }
                            })
                            //向发送消息
                            EMClient.getInstance().chatManager().sendMessage(emMessage)
                        }
                    }
                }
            }, verticalArrangement = Arrangement.spacedBy(10.dp))

            if (messageString.equals("爱你")) {
                LoveView()
            }

            if (isShowBottomDialog) {
                ModalBottomSheet(
                    onDismissRequest = { isShowBottomDialog = false },
                    modifier = Modifier.height(300.dp)
                ) {
                    LazyVerticalGrid(columns = GridCells.Fixed(4), content = {
                        item {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(10.dp),
                                modifier = Modifier.clickable {
                                    navHostController.navigate(RoutePath.MAP)
                                }
                            ) {
                                Icon(imageVector = Icons.Default.LocationOn, contentDescription = "")
                                Text(text = "位置")
                            }
                        }
                    })
                }
            }
        }
    }
}

@Composable
fun LoveView() {
    AndroidView(factory = {
        val redPackRainView = RedPackRainView(it)
        redPackRainView.start()
        redPackRainView
    }, modifier = Modifier.fillMaxSize())
}

@Composable
fun ChatItem(
    message: EMMessage,
    isShowProgress: Boolean,
    isLast: Boolean,
    isError: Boolean,
    isShowTime: Boolean,
    retry: () -> Unit
) {
    if (message.direct() == EMMessage.Direct.SEND) {
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
            if (isShowTime) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = time, color = Color.LightGray, fontSize = 13.sp)
            }
            Row(
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
            ) {
                //当展示进度条并且是最后一条的时候才会展示
                if (isShowProgress && isLast) {
                    CircularProgressIndicator(Modifier.size(20.dp))
                }

                if (isLast && isError) {
                    Text(text = "点击重发", fontSize = 12.sp, color = Color.LightGray)
                    Icon(
                        painter = painterResource(id = R.drawable.baseline_error_24),
                        contentDescription = "",
                        tint = Color.Red, modifier = Modifier.clickable {
                            retry()
                        }
                    )
                }
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = (message.body as EMTextMessageBody).message)
                Spacer(modifier = Modifier.width(10.dp))
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(5.dp)),
                    contentScale = ContentScale.Crop
                )
            }
        }
    } else {
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
            Text(text = "10:30", color = Color.LightGray, fontSize = 13.sp)
            Row(
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
            ) {
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(5.dp)),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = (message.body as EMTextMessageBody).message)
            }
        }
    }

}